@page "/login"
@layout Layout.EmptyLayout
@rendermode InteractiveServer

<EditForm Model="@_model" OnValidSubmit="OnLoginSubmit">
    <DataAnnotationsValidator/>
    <MudGrid Justify="Justify.Center">
        <MudItem xs="12" sm="6" md="4">
            <MudCard>
                <MudCardHeader>
                    <CardHeaderAvatar>
                        <MudAvatar Color="Color.Secondary">Hi</MudAvatar>
                    </CardHeaderAvatar>
                    <CardHeaderContent>
                        <MudText Typo="Typo.body1">熊猫管理系统</MudText>
                        <MudText Typo="Typo.body2">请您登录后继续！</MudText>
                    </CardHeaderContent>
                </MudCardHeader>
                <MudCardContent>
                    <MudTextField Label="电子邮件" Class="mt-3" @bind-Value="_model.Email"
                                  For="() => _model.Email"></MudTextField>
                    <MudTextField Label="密码" Class="mt-3" @bind-Value="_model.Password"
                                  For="() => _model.Password" InputType="@_passwordInput"
                                  Adornment="Adornment.End" AdornmentIcon="@_passwordInputIcon"
                                  OnAdornmentClick="ShowPassword"></MudTextField>
                </MudCardContent>
                <MudCardActions>
                    <MudButton Color="Color.Primary" ButtonType="ButtonType.Submit" Variant="Variant.Filled"
                               Class="ml-auto">登录
                    </MudButton>
                </MudCardActions>
            </MudCard>
        </MudItem>
    </MudGrid>
</EditForm>

@code {
    private readonly LoginData _model = new();
    private bool _isShow;
    private InputType _passwordInput = InputType.Password;
    private string _passwordInputIcon = Icons.Material.Filled.VisibilityOff;

    private void ShowPassword()
    {
        if (_isShow)
        {
            _passwordInput = InputType.Password;
            _passwordInputIcon = Icons.Material.Filled.VisibilityOff;
        }
        else
        {
            _passwordInput = InputType.Text;
            _passwordInputIcon = Icons.Material.Filled.Visibility;
        }

        _isShow = !_isShow;
    }

    private async Task OnLoginSubmit(EditContext obj)
    {
        var loginResult = await AccountService.LoginAsync(_model);
        if (loginResult.IsSuccess)
        {
            var customAuthStateProvider = (CustomAuthenticationStateProvider)AuthStateProvider;
            customAuthStateProvider.UpdateAuthenticationState(loginResult.Token);
            StateHasChanged();
            NavManager.NavigateTo("/");
        }
        else
        {
            Snackbar.Add(loginResult.Message!, Severity.Error);
        }
    }

}